<template>
  <div class="card-price-editor">
    <div class="card-price-header">
      <h2>{{ title }}</h2>
      <el-button type="primary" @click="addRow">{{ btnText }}</el-button>
    </div>
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
    >
      <el-row v-for="(item, index) in form.cards" :key="index">
        <el-col :span="8">
          <el-form-item prop="times">
            <el-input v-model="item.times" placeholder="次卡次数" />
            <div slot="append">次</div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="price">
            <el-input v-model="item.price" placeholder="售价" />
            <div slot="append">元</div>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="originPrice">
            <el-input v-model="item.originPrice" placeholder="原价" />
            <div slot="append">元</div>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="validDays">
            <el-input v-model="item.validDays" placeholder="有效期" />
            <div slot="append">天</div>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="remove-btn-container">
          <el-button type="danger" @click.prevent="removeRow(index)">删除</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { ElForm, ElRow, ElCol, ElInput, ElButton, ElFormItem } from 'element-plus';

export default defineComponent({
  name: 'CardPriceEditor',
  components: {
    ElForm,
    ElRow,
    ElCol,
    ElInput,
    ElButton,
    ElFormItem,
  },
  props: {
    title: {
      type: String,
      default: '设置价格',
    },
    btnText: {
      type: String,
      default: '增加梯度',
    },
  },
  setup(props) {
    const form = {
      cards: [
        {
          times: '',
          price: '',
          originPrice: '',
          validDays: '',
        },
      ],
    };
    const rules = {
      times: [{ required: true, message: '请输入次卡次数', trigger: 'blur' }],
      price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
      originPrice: [{ required: true, message: '请输入原价', trigger: 'blur' }],
      validDays: [{ required: true, message: '请输入有效期', trigger: 'blur' }],
    };

    function addRow() {
      form.cards.push({
        times: '',
        price: '',
        originPrice: '',
        validDays: '',
      });
    }

    function removeRow(index: number) {
      form.cards.splice(index, 1);
    }

    return {
      form,
      rules,
      addRow,
      removeRow,
    };
  },
});
</script>

<style scoped>
.card-price-editor {
  max-width: 100%;
  margin: 0 auto;
}

.card-price-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.remove-btn-container {
  display: flex;
  justify-content: flex-end;
}
</style>